package com.imedway.ihe.dd.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.support.DefaultExchange;
import org.openehealth.ipf.commons.ihe.xds.core.SampleData;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.ProvideAndRegisterDocumentSetRequestType;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.AvailabilityStatus;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.DocumentEntry;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.Identifiable;
import org.openehealth.ipf.commons.ihe.xds.core.requests.ProvideAndRegisterDocumentSet;
import org.openehealth.ipf.commons.ihe.xds.core.requests.QueryRegistry;
import org.openehealth.ipf.commons.ihe.xds.core.requests.RegisterDocumentSet;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.QueryReturnType;
import org.openehealth.ipf.commons.ihe.xds.core.responses.QueryResponse;
import org.openehealth.ipf.commons.ihe.xds.core.responses.Response;
import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.lcm.SubmitObjectsRequest;
import org.openehealth.ipf.platform.camel.core.util.Exchanges;
import org.openehealth.ipf.platform.camel.ihe.xds.core.converters.EbXML30Converters;
import org.openehealth.ipf.platform.camel.ihe.xds.core.converters.XdsRenderingUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.activation.DataHandler;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import static com.imedway.ihe.constant.Constants.ITI18_ENDPOINT_URL;
import static com.imedway.ihe.constant.Constants.ITI41_ENDPOINT_URL;
import static com.imedway.ihe.constant.Constants.ITI42_ENDPOINT_URL;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/7/4
 */
@Slf4j
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {

    private final CamelContext camelContext;
    private final ProducerTemplate producerTemplate;

    @PostMapping(value = "iti41", consumes = "application/json")
    public String iti4142ProvidedAndRegister() throws Exception {
        Exchange exchange = new DefaultExchange(camelContext);
        exchange.setPattern(ExchangePattern.InOut);

        // 构建文档
        ProvideAndRegisterDocumentSet provide = SampleData.createProvideAndRegisterDocumentSet();
        DocumentEntry documentEntry = provide.getDocuments().get(0).getDocumentEntry();

        Identifiable patientId = documentEntry.getPatientId();
        HashMap<String, List<String>> extra = new HashMap<>();
        extra.put("urn:abc", CollUtil.newArrayList("ddd"));
        documentEntry.setExtraMetadata(extra);
        patientId.setId(UUID.randomUUID().toString());
        log.debug(patientId.getId());
        documentEntry.setUniqueId("4.3.2.1");

//        documentEntry.setHash(String.valueOf(ContentUtils.sha1(provide.getDocuments().get(0).getContent(DataHandler.class))));
//        documentEntry.setSize(Long.valueOf(String.valueOf(ContentUtils.size(provide.getDocuments().get(0).getContent(DataHandler.class)))));

        provide.getDocuments().get(0).setDocumentEntry(documentEntry);

        log.debug(String.valueOf(provide.getDocuments().size()));
        log.debug(provide.getDocuments().get(0).getDocumentEntry().getEntryUuid());
        log.debug(provide.getDocuments().get(0).getDocumentEntry().getUniqueId());
        log.debug(String.valueOf(provide.getDocuments().get(0).getDocumentEntry().getSize()));

        // 发送请求
        exchange.getIn().setBody(provide);
        String request = XdsRenderingUtils.render(exchange);
        // 发送到具体路由
//        exchange = producerTemplate.send("xds-iti41://192.168.75.128:8010/axis2/services/xdsrepositoryb.xdsrepositorybHttpSoap12Endpoint/", exchange);
        exchange = producerTemplate.send("xds-iti41://127.0.0.1:8080/services/iti41", exchange);

        // 返回的异常信息
        Exception exception = Exchanges.extractException(exchange);
        if (exception != null) {
            throw exception;
        }

        // 返回的结果信息
        Response response1 = exchange.getMessage().getMandatoryBody(Response.class);
        log.warn(response1.toString());

        return "完成";
    }

    @PostMapping(value = "test2-iti41", consumes = "application/json")
    public String test2() throws Exception {
        Exchange exchange = new DefaultExchange(camelContext);
        exchange.setPattern(ExchangePattern.InOut);

        RegisterDocumentSet registerDocumentSet = SampleData.createRegisterDocumentSet();
        log.warn("当前注册文档集的大小为为:"+registerDocumentSet.getDocumentEntries().size());
        DocumentEntry documentEntry = registerDocumentSet.getDocumentEntries().get(0);

        documentEntry.getAuthors().get(0).getAuthorTelecom().set(0, null);
        documentEntry.getAuthors().get(0).getAuthorTelecom().set(1, null);
        documentEntry.setMimeType(ContentType.TEXT_XML.getValue());

        // 添加患者信息
        Identifiable patientId = documentEntry.getPatientId();
        patientId.setId(UUID.randomUUID().toString());
        log.warn(patientId.getId());
        // 设置文档唯一ID
        documentEntry.setUniqueId("4.3.2.1");

        registerDocumentSet.getDocumentEntries().set(0,documentEntry);
        // 查看值是否设置进去
        log.info(registerDocumentSet.getDocumentEntries().get(0).getUniqueId());
        log.info(registerDocumentSet.getDocumentEntries().get(0).getUri());
        log.info(registerDocumentSet.getDocumentEntries().get(0).getPatientId().getId());

        // 发送请求
        exchange.getIn().setBody(registerDocumentSet);

        log.debug(XdsRenderingUtils.render(exchange));

        exchange = producerTemplate.send("xds-iti42://192.168.75.128:8010/axis2/services/xdsregistryb.xdsregistrybHttpSoap12Endpoint/", exchange);
//        log.error(XdsRenderingUtils.render(exchange));

        Exception exception = Exchanges.extractException(exchange);
        if (exception != null) {
            throw exception;
        }
        Response providedResponse = exchange.getMessage().getMandatoryBody(Response.class);
        log.warn(providedResponse.toString());
        return "";
    }

}
